<template>
  <view class="MessAge">
    <uni-nav-bar left-icon="left" title="来访登记" />
    <div class="vister-rigister">
      <!-- <div class="leftarrows"><span class="iconfont">&#xe65a;</span></div> -->
      <van-nav-bar title="来访登记" left-arrow />
      <div class="visitor-register-left">
        <view class="left-view">
          <text>来访登记</text>
          <text>来访人员请注意配合登记</text>
        </view>
      </div>
    </div>
    <!-- 表单区域组件 -->
    <!-- :rules="customRules" -->
    <uni-forms ref="customForm" :model="formData" label-position="top" validateTrigger="blur">
      <uni-forms-item label="日期" name="date">
        <uni-datetime-picker type="datetime" return-type="timestamp" v-model="baseFormData.datetimesingle" />
      </uni-forms-item>
      <uni-forms-item required label="姓名" name="name" props="data">
        <uni-easyinput prefixIcon="person" type="text" v-model="formData.name" placeholder="请输入您的姓名" />
      </uni-forms-item>

      <uni-forms-item required label="身份证号" name="id_number">
        <uni-easyinput prefixIcon="wallet" type="text" v-model="formData.id_number" placeholder="请输入您的身份证号" />
      </uni-forms-item>
      <uni-forms-item required label="手机号" name="phone">
        <uni-easyinput v-if="formData.phone" prefixIcon="wallet" type="tel" v-model="formData.phone"
          placeholder="请输入手机号" />
        <button v-else open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
          <uni-icons type="phone-filled" size="20"></uni-icons>点击授权手机号</button>
      </uni-forms-item>
      <view class="title"> 车牌号码</view>
      <Plate :plateNumber="plateNumber" @myPlateChange="plateChange" />
      <!-- <button class="submit" @click="handleSave">保存</button> -->
      <uni-forms-item required label="受访人姓名" name="visitorname" class="bisitoe-name">
        <uni-easyinput type="text" v-model="formData.visitorname" placeholder="请输入" />
      </uni-forms-item>
      <uni-forms-item required label="来访事由" name="visitorreason">
        <uni-easyinput type="textarea" v-model="formData.visitorreason" placeholder="请输入" />
      </uni-forms-item>

    </uni-forms>
    <uni-section title="需自拍照片上传" type="line">
      <view class="example-body">
        <uni-file-picker v-model="imageValue" limit="1" title="至少1张" fileMediatype="image" disable-preview="true"
          del-icon="true" sourceType mode="grid" @select="select" @success="success" @fail="fail"
          @delete="deletfile"></uni-file-picker>
      </view>
    </uni-section>
    <!-- 以下是弹框模板 -->
    <!-- —————————————————————————————————————————————————————————————————————————————————————————————————————————————— -->
    <button @click="submitForm('customForm')" class="uni-button">登记</button>
    <view class="viewdetail"><text>提交即授权该表单手机你填写的信息，</text>
      <navigator class="detail" url="" @click="dialogToggle">查看详情</navigator>
    </view>
    <!-- 提示窗示例 -->
    <view>
      <!-- 提示窗示例 -->
      <uni-popup ref="alertDialog" type="dialog">
        <uni-popup-dialog :type="msgType" cancelText="关闭" confirmText="确定" title="表单填写须知" content="欢迎使用 uni-popup!">
          <template>
            <view class="template-detail-top">当您天填写表单时，表单中可能包含表单创建者设定、需要您主动填写个人信息。例如：姓名、身份证号 等</view>
            <view class="template-detail-center">
              您一旦主动填写并提交后，即视为您授权该表单收集您填写的信息，相关个人信息即归于表单创建者控制。
              您应当自行判断提供个人信息的相应风险。如您拒绝想表单创建者提供个人信息，请勿填写并提交表单。
              如果您对以上表单创建者控制的个人信息的收集目的、范围和使用方式有任何疑问或者一件，您理解并同意联系该表单创建者处理
            </view>
            <view class="more-detail">
              <text>更多详细信息，请查看</text>
              <navigator :url="'/subpkg/agreement-detail/agreement-detail'">《隐私协议》</navigator>
            </view>
          </template>
        </uni-popup-dialog>
      </uni-popup>
      <!--  <uni-section title="对话框示例" type="line" class="hideOnPc">
        <view class="example-body box"> -->
      <!--    <button class="button popup-success" @click="dialogToggle('success')"><text
              class="button-text success-text">成功</text></button> -->
      <!--  </view>
      </uni-section> -->
    </view>
  </view>
</template>

<script>
  import Plate from '@/components/platenumber/platenumber.vue'
  export default {
    components: {
      Plate
    },
    data() {
      return {
        ACCESS_TOKEN: '', // 入口编码
        datetimesingle: '', //日期显示作用
        // 换取成功后 暂存这些数据 留作后续操作 
        session_key: '', //session_key  会话密钥  
        plateNumber: ['', '', '', '', '', '', '', ''],
        imageValue: [], // 拍照上传图片存储的数据字段
        formData: {
          date: '', // 存储时间日期
          name: '',
          phone: '', // 存储获取用户的手机号字段
          id_number: '', //存储身份证号字段
          visitorname: '',
          visitorreason: ''
        },
        customRules: {
          name: {
            rules: [{
              required: true,
              errorMessage: '姓名不能为空'
            }]
          },
          id_number: {
            rules: [{
                required: true,
                errorMessage: '请填写身份证号'
              },
              {
                validateFunction: function(rule, value, data, callback) {
                  if (value.length < 18 || value.length > 18) {
                    callback('身份证号不正确')
                  }
                  return true
                }
              }
            ]
          },
          visitorname: {
            rules: [{
              required: true,
              errorMessage: '访客姓名不能为空'
            }]
          },
          visitorreason: {
            rules: [{
              required: true,
              errorMessage: '来访事由不能为空'
            }]
          }
        },
      };
    },
    onLoad() {
      this.getAccessToken()
      console.log(this.uploadFile)
    },
    onReady() {
      // 需要在onReady中设置规则
      this.$refs.customForm.setRules(this.customRules)
      // this.getuserNew(); //   获取openid
    },
    methods: {
      // 获取access_token
      getAccessToken() {
        uni.request({
          url: 'https://api.weixin.qq.com/cgi-bin/token',
          method: 'GET',
          data: {
            grant_type: "client_credential", //这个是固定的
            appid: 'wx0cd44ab5265f7f4a',
            secret: 'e0388d9679db3833f248c05421a7ef58'
          },
          success: (res) => {
            console.log(res, 'token')
            this.ACCESS_TOKEN = res.data.access_token
          }
        })
      },
      //点击buttonbindgetphonenumber回调获取动态code,,然后把code传到开发者后台，
      //并在开发者后台调用微信后台提供的 phonenumber.getPhoneNumber 接口，消费code来换取用户手机号
      getPhoneNumber(e) {
        let code = e.detail;
        console.log(detail, '4444');
        if (detail.errMsg === "getPhoneNumber:ok") {
          console.log('用户同意授权');
          let code = detail.code; // 动态令牌
          this.getPhoneNumber(code)
        } else {
          console.log('用户拒绝授权');
        }
      },
      getPhoneNumber(code) {
        uni.request({
          url: "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + this.ACCESS_TOKEN,
          method: 'POST',
          data: {
            code: code.detail.code
          },
          success: (res) => {
            this.formData.phone = res.data.phone_info.phoneNumber
          }
        })
      },

      // 车牌功能函数
      plateChange(val) {
        this.plateNumber = val;
      },

      // __________________________________________
      dialogbutton() {
        this.dialogToggle()
      },
      dialogToggle(type) {
        this.msgType = type
        this.$refs.alertDialog.open()
      },
// 获取上传状态
      select(e) {
        uni.showModal({
          title:'图片正在上传',
        })
        //e  拍照上传的文件路径, 把这个文件路径上传到服务器，如果上传成功就调用上传成功的函数，失败就调用失败的回调函数
        uni.uploadFile({
          url: 'https://qrcode.qgfhrz.cn/adminApi/file/uploadImage', //仅为示例，非真实的接口地址
          filePath: e.tempFilePaths[0],
          name: 'file',
          success: (uploadFileRes) => {
            const array1 = uploadFileRes.data.substring(32, 49)
           this.success(array1)
          }
        });
      },
      // 上传成功
      success(array1) {
        this.imageValue = array1
       uni.showModal({
         title:'图片上传成功',
       })
       this.tag = 1
      },

      // 上传失败
      fail(e) {
        console.log('上传失败：', e)
      },
      // 删除图片时清零字符串
      deletfile() {
        this.tempFilePaths = ''
      },
      // 表单提交成功的处理逻辑
      submitForm(customForm) {
        let plate = ""; // 车牌号获取成功
        this.plateNumber.forEach((item, index) => {
          if (index === 1) {
            plate = plate + item + "·";
          } else {
            plate += item;
          }
        })
        console.log(plate, '车牌号一');
        this.plateNumber = plate
        // 表单校验
        this.$refs.customForm.validateField(['name', 'id_number', 'visitorname', 'visitorreason']).then((res) => {
          this.submit()
        }).catch((error) => {

        })

      },
      submit() {
        // 整理参数传递发起网咯数据请求
        var requestData = {
          name: this.formData.name,
          idCard: this.formData.id_number,
          phone: this.formData.phone,
          licensePlate: this.plateNumber,
          intervieweeName: this.formData.visitorname,
          reason: this.formData.visitorreason,
          img: this.imageValue
        };
        uni.request({
          url: 'https://qrcode.qgfhrz.cn/adminApi/visitor/visitorAdd2', //仅为示例，非真实的接口地址
          data: requestData,
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success: (uploadFileRes) => {
            if (uploadFileRes.data.code == 200) {
              //   // 表单提交成功之后跳转到照片展示页面、subpkg/show-photo/show-photo
              uni.navigateTo({
                url: '/subpkg/show-photo/show-photo'
              })
            } else {
              uni.showToast({
                title: `提交失败`
              })
            }
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  .visitor-register-left {
    margin: 30px 0;
    padding: 0 10px;
    width: 262px;
    font-size: 13px;
    color: #8c8c8c;

    .left-view {
      display: flex;
      flex-direction: column;
    }

    .left-view :nth-child(1) {
      font-size: 23px;
      font-weight: 700;
      margin-bottom: 5px;
      color: #0088d1;
    }
  }

  .uni-button {
    background-color: #166bc7;
    color: #fff;
    margin: 0 10px;
    margin-top: 30px;
  }

  .viewdetail {
    width: 300px;
    height: 100px;
    font-size: 13px;
    color: #8c8c8c;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;

    .detail {
      color: #166bc7;
    }
  }

  .uni-dialog-button:first-child {
    display: none;
  }

  navigator {
    color: #608dc0;
  }

  .uni-dialog-content {
    display: flex;
    flex-direction: column !important;
  }

  .template-detail-top {
    // background-color: pink;
  }

  .template-detail-center {
    // background-color: #0088d1;
    margin: 30px 0;
  }

  .more-detail {
    display: flex;
    flex-direction: row;
  }

  .uni-easyinput__content-input {
    height: 56px !important;
  }

  .uni-forms {
    padding: 0 10px;
  }

  .uni-section {
    margin: 0 10px;
  }


  .title {
    height: 104rpx;
    line-height: 104rpx;
    font-family: PingFangSC-Regular;
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.90);

    .icon {
      font-size: 32rpx;
      color: #FA3239;
      vertical-align: middle;
      margin-left: 4rpx;
    }
  }

  // .submit {
  //   width: 100%;
  //   height: 96rpx;
  //   line-height: 96rpx;
  //   background: #02BA94;
  //   border-radius: 16rpx;
  //   color: #FFFFFF;
  //   font-size: 34rpx;
  //   margin-top: 48rpx;
  //   bottom: 48rpx;
  //   position: absolute;
  // }
  .data-v-5af46e78 {
    margin-bottom: 20px;
  }

  .panel .header.data-v-5af46e78 {
    height: 157px !important;
  }

  .uni-date__x-input {
    height: 57px !important;
    line-height: 57px !important;
  }
</style>